package com.flashcash.solu.view.presenter;

import android.Manifest;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import com.flashcash.kotlin.data.ProductBean;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.presenter.BaseActivityPresenterImpl;
import com.flashcash.solu.bean.AppEntity;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.bean.MarketApp;
import com.flashcash.solu.bean.ProgressBean;
import com.flashcash.solu.bean.ResponseErrorBody;
import com.flashcash.solu.bean.UserInfoEntity;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.common.update.UpdateManager;
import com.flashcash.solu.harvester.TraceSender;
import com.flashcash.solu.harvester.store.StoreUtils;
import com.flashcash.solu.utils.ACache;
import com.flashcash.solu.view.MainActView;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.x.leo.apphelper.data.cache.CacheDataManage;
import com.x.leo.apphelper.log.XLog;

import java.util.ArrayList;

import okhttp3.ResponseBody;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @作者:My
 * @创建日期: 2017/6/21 18:10
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${git}
 */

public class MainActPreImp extends BaseActivityPresenterImpl implements MainActPresenter {
    private Pair<LatestLoanAppBean, ArrayList<ProductBean>> pair;

    @Override
    public void requestAndUploadPrivacyInfo() {
        try {
            if (!isAttached()) {
                return;
            }
            new RxPermissions(mView.getBaseActivity())
                    .request(Manifest.permission.READ_PHONE_STATE,  //call log
                            Manifest.permission.READ_CONTACTS,      //contact
                            //Manifest.permission.READ_SMS,       //sms
                            Manifest.permission.ACCESS_COARSE_LOCATION)
                    .subscribe(new Subscriber<Boolean>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable throwable) {
                        }

                        @Override
                        public void onNext(Boolean b) {
                            StoreUtils.collectAndSaveLocation(mView.getBaseActivity());

                            rx.Observable.just(1)
                                    .subscribeOn(Schedulers.io())
                                    .map(t -> {
                                        StoreUtils.getAllSync(mView.getBaseActivity());
                                        return 1;
                                    })
                                    .subscribe(new Subscriber<Integer>() {
                                        @Override
                                        public void onCompleted() {
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                        }

                                        @Override
                                        public void onNext(Integer integer) {
                                        }
                                    });

                            Log.d("permissionxxx", "" + b.toString());
                        }
                    });
        } catch (Exception e) {
            XLog.INSTANCE.d("Exception: " + e.getMessage(), 10);
        }
    }

    @Override
    public void requestProductsDefault() {
        showLoading(null);
        mUserApi.getProductsDefault()
                .subscribeOn(Schedulers.io())
                .compose(((MainActView) mView).bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ArrayList<ProductBean>>() {

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        ((MainActView) mView).onResponseProductsDefaultError(e.getMessage());
                    }

                    @Override
                    public void onNext(ArrayList<ProductBean> productBeanList) {
                        dismissLoading();
                        dealProducts(productBeanList);
                    }
                });
    }

    @Override
    public void requestLatestAndProducts() {
        showLoading(null);
        mUserApi.getLatestLoanApp(TokenManager.getInstance().getToken(), "MainActivity")
                .zipWith(mUserApi.getProducts(TokenManager.getInstance().getToken()), Pair::create)
                .subscribeOn(Schedulers.io())
                .compose(((MainActView) mView).bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Pair<LatestLoanAppBean, ArrayList<ProductBean>>>() {

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        ((MainActView) mView).onResponseLatestAndProductsError(e.getMessage());
                    }

                    @Override
                    public void onNext(Pair<LatestLoanAppBean, ArrayList<ProductBean>> pair) {
                        dismissLoading();
                        MainActPreImp.this.pair = pair;
                        CacheDataManage.INSTANCE.addData(FieldParamsInt.LATESTBEAN, pair.first);
                        dealLatestAndProducts();
                    }
                });
    }

    /**
     * firstly judge latest, finally judge products
     */
    @Override
    public void dealLatestAndProducts() {
        LatestLoanAppBean latestLoanAppBean = pair.first;
        ArrayList<ProductBean> productBeanList = pair.second;

        if (latestLoanAppBean == null) { // show Fragment according to products
            dealProducts(productBeanList);
        } else if (FieldParams.LoanStatus.OVERDUE.equals(latestLoanAppBean.getStatus())) { //
            // show LoanRepaymentExpiryFragment
            ((MainActView) mView).showLoanRepayExpiry();
        } else if (FieldParams.LoanStatus.CURRENT.equals(latestLoanAppBean.getStatus())) { //
            // only show loanSuccess dialog once and show LoanRepaymentFragment
            String loanAppId = ACache.get(mView.getBaseActivity()).getAsString(FieldParams
                    .ACacheKeys.ACACHE_LOAN_RESULT);
            if (!TextUtils.equals(loanAppId, latestLoanAppBean.getLoanAppId())) { // only show
                // loanSuccess dialog once
                ACache.get(mView.getBaseActivity()).put(FieldParams.ACacheKeys.ACACHE_LOAN_RESULT, latestLoanAppBean
                        .getLoanAppId());
                ((MainActView) mView).showLoanSuccess();
            }
            // show LoanRepaymentFragment
            ((MainActView) mView).showLoanRepay();
        } else if (FieldParams.LoanStatus.SUBMITTED.equals(latestLoanAppBean.getStatus())) { //
            // show Fragment according to products
            dealProducts(productBeanList);
        } else if (FieldParams.LoanStatus.IN_REVIEW.equals(latestLoanAppBean.getStatus()) ||
                FieldParams.LoanStatus.READY_TO_ISSUE.equals(latestLoanAppBean.getStatus()) ||
                FieldParams.LoanStatus.APPROVED.equals(latestLoanAppBean.getStatus()) ||
                FieldParams.LoanStatus.ISSUE_FAILED.equals(latestLoanAppBean.getStatus()) ||
                FieldParams.LoanStatus.ISSUING.equals(latestLoanAppBean.getStatus())) { // show
            // LoanInProcessFragment
            ((MainActView) mView).showLoanInProcess();
        } else if (FieldParams.LoanStatus.NOLOANAPP.equals(latestLoanAppBean.getStatus()) ||
                FieldParams.LoanStatus.CANCELED.equals(latestLoanAppBean.getStatus()) ||
                FieldParams.LoanStatus.PAID_OFF.equals(latestLoanAppBean.getStatus())) { // show
            // Fragment according to products
            dealProducts(productBeanList);
        } else if (FieldParams.LoanStatus.REJECTED.equals(latestLoanAppBean.getStatus())) { //
            // only show loanReject dialog once and show Fragment according to products
            String loanAppId = ACache.get(mView.getBaseActivity()).getAsString(FieldParams
                    .ACacheKeys.ACACHE_LOAN_RESULT);
            if (!TextUtils.equals(loanAppId, latestLoanAppBean.getLoanAppId())) { // only show
                // loanReject dialog once
                ACache.get(mView.getBaseActivity()).put(FieldParams.ACacheKeys.ACACHE_LOAN_RESULT, latestLoanAppBean
                        .getLoanAppId());
                ((MainActView) mView).showLoanReject();
            }
            // show Fragment according to products
            dealProducts(productBeanList);
        } else if (FieldParams.LoanStatus.CLOSED.equals(latestLoanAppBean.getStatus())) { // only
            // show loanClosed dialog once and show Fragment according to products
            String loanAppId = ACache.get(mView.getBaseActivity()).getAsString(FieldParams
                    .ACacheKeys.ACACHE_LOAN_RESULT);
            if (!TextUtils.equals(loanAppId, latestLoanAppBean.getLoanAppId())) { // only show
                // loanClosed dialog once
                ACache.get(mView.getBaseActivity()).put(FieldParams.ACacheKeys.ACACHE_LOAN_RESULT, latestLoanAppBean
                        .getLoanAppId());
                ((MainActView) mView).showLoanClosed(latestLoanAppBean);
            }
            // show Fragment according to products
            dealProducts(productBeanList);
        } else { // show Fragment according to products
            dealProducts(productBeanList);
        }
    }

    private void dealProducts(ArrayList<ProductBean> productBeanList) {
        if (productBeanList != null && !productBeanList.isEmpty()) {
            if (productBeanList.size() == 1) { // show LoanNormalFragment
                ((MainActView) mView).showLoanNormal(productBeanList.get(0));
            } else { // show ProductFragment
                ((MainActView) mView).showLoanProducts(productBeanList);
            }
        } else { // show error and can retry
            ((MainActView) mView).onResponseLatestAndProductsError(mView.getBaseActivity().getString(R.string.empty_product));
        }
    }

    @Override
    public void updateApk(EventCollection.NeedUpdateEvent event) {
        XLog.INSTANCE.i("VERSION_CHECK0" + " updateApk:" + event.toString(), 12);
        new UpdateManager(mView.getBaseActivity(), event).start();
    }

    @Override
    public void requestMarket() {
//        mUserApi.getMarket("flashcashloan")
        mUserApi.getMarket(new AppEntity("flashcash"))
                .subscribeOn(Schedulers.io())
                .compose(((MainActView) mView).bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MarketApp>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ((MainActView) mView).onResponseLatestAndProductsError(e.getMessage());
                    }

                    @Override
                    public void onNext(MarketApp marketApp) {//把获取到的缓存起来
                        CacheDataManage.INSTANCE.addData(FieldParamsInt.MARKET_APP, marketApp);
                    }
                });
    }

    @Override
    public void addUserInfo(String mobile, String blackbox) {
        final MainActView view = (MainActView) mView;
        showLoading(null);
        mUserApi.addUserInfo(new UserInfoEntity(mobile, blackbox, TraceSender.getAndroidID(mView.getBaseActivity())))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        XLog.INSTANCE.e("请求错误", e, 12);
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        dismissLoading();
                        view.onAddUserInfoSuccess();
//                        XLeoToast.showMessage("添加用户成功");
                    }
                });
    }

    @Override
    public void updateCertifyState() {
        final MainActView view = (MainActView) mView;
        showLoading(null);
        mUserApi.progress(TokenManager.getInstance().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ProgressBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                    }

                    @Override
                    public void onNext(ProgressBean progressBean) {
                        dismissLoading();
                        view.updateCertifyStateSuccess(progressBean);
                    }
                });
    }

    @Override
    public void isQualification(ProductBean productBean) {
        showLoading("");
        mUserApi.isQualification(TokenManager.getInstance().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseErrorBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {//显示需要多少天之后才能申请
                        dismissLoading();
                        Gson gson = new Gson();
                        if (e instanceof HttpException) {
                            HttpException httpException = (HttpException) e;
                            String errorBody = null;
                            try {
                                errorBody = httpException.response().errorBody().string();
                                ResponseErrorBody responseErrorBody = gson.fromJson(errorBody, ResponseErrorBody.class);
                                if (isAttached()) {
                                    if (!TextUtils.isEmpty(responseErrorBody.getMessage())) {
//                                        XLeoToast.showMessage("返回的数据："+responseErrorBody.getMessage());
                                        ((MainActView) mView).qualification(responseErrorBody.getMessage(), productBean);
                                    }
                                }
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }

                        }
                        /*else {
                            XLeoToast.showMessage(R.string.show_netwok_wrong);
                        }*/
                    }

                    @Override
                    public void onNext(ResponseErrorBody responseErrorBody) {
                        dismissLoading();
                        ((MainActView) mView).qualification("", productBean);
                    }
                });
    }
}
